package com.huang.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.huang.enums.UserCodeEnum;
import com.huang.resp.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 自定义鉴权失败
 *
 * @author han
 * @since 2022-01-16 16:19:01
 */
@Slf4j
@Component
public class DefaultAccessDeniedHandler implements ServerAccessDeniedHandler {


    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange, AccessDeniedException e) {
        log.info(" ======》账号无权限《=========");
        return Mono.defer(() -> Mono.just(serverWebExchange.getResponse()).flatMap(response -> {
            response.setStatusCode(HttpStatus.OK);
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

            DataBufferFactory dataBufferFactory = response.bufferFactory();
            String result = JSONObject.toJSONString(CommonResult.error(UserCodeEnum.PERMISSION_DENIED));
            DataBuffer dataBuffer = dataBufferFactory.wrap(result.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));
        }));
    }
}
